package com.xhai.security.filter;

import com.xhai.admin.service.TokenService;
import com.xhai.common.constant.RequestConstants;
import com.xhai.common.utils.classes.StringUtils;
import com.xhai.security.wrapper.DecryptedRequestWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author xhai
 * @description 登录表单信息解密过滤器
 * @date 2025/6/7
 */
public class LoginFormDecryptFilter extends OncePerRequestFilter {

    @Resource
    private TokenService tokenService;

    @Value("${admin.frontend.decrypt-key}")
    private String frontendDecryptKey;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 只处理/login，并且未携带token
        String token = tokenService.getToken(request);
        if (RequestConstants.REQUEST_URI_LOGIN.equals(request.getRequestURI())
                && StringUtils.isEmpty(token)) {
            filterChain.doFilter(new DecryptedRequestWrapper(request, frontendDecryptKey), response);
        }

        filterChain.doFilter(request, response);
    }
}
